﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NFox.Basal
{
    /// <summary>
    /// 字符串扩展函数
    /// </summary>
    public static class StringEx
    {
        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns><see langword="true"/> 为占用，<see langword="false"/> 为未占用</returns>
        public static bool IsFileUsed(this string fileName)
        {
            bool inUse = true;
            if (File.Exists(fileName))
            {
                FileStream fs = null;
                try
                {
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                    inUse = false;
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                return inUse;           //true表示正在使用,false没有使用
            }
            else
            {
                return false;           //文件不存在则一定没有被使用
            }
        }
        /// <summary>
        /// 字符串重复
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="n">重复次数</param>
        /// <returns>重复后的字符串</returns>
        public static string Repeat(this string str, int n)
        {
            var values = new char[n * str.Length];
            values.Fill(str.ToCharArray());
            return new string(values);
        }
        /// <summary>
        /// 数组充填函数
        /// </summary>
        /// <typeparam name="T">数组的类型泛型</typeparam>
        /// <param name="destinationArray">要充填的数组</param>
        /// <param name="value">充填的数据</param>
        public static void Fill<T>(this T[] destinationArray, params T[] value)
        {
            if (destinationArray == null)
            {
                throw new ArgumentNullException("destinationArray");
            }

            if (value.Length > destinationArray.Length)
            {
                throw new ArgumentException("Length of value array must not be more than length of destination");
            }

            // set the initial array value
            Array.Copy(value, destinationArray, value.Length);

            int copyLength, nextCopyLength;

            for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
            {
                Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
            }

            Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
        }
    }
}
